package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.Utilities;
import beans.Examinationbean;
import beans.KnowledgePointbean;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import dao.Course;
import dao.Examination;
import dao.Knowledgepoint;

public class ExaminationManagerServlet extends HttpServlet {

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {

	this.doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {

	if (request.getQueryString() != null) {
	    String actionString = request.getParameter("action").trim();
	    if ("add".equals(actionString)) {
		StringBuffer pathString;
		SmartUpload su = new SmartUpload();
		su.initialize(this.getServletConfig(), request, response);
		su.setMaxFileSize(2000000);
		su.setAllowedFilesList("jpg,jpeg,png");
		try {
		    su.upload();
		} catch (SmartUploadException e) {
		    e.printStackTrace();
		}
		Request request2 = su.getRequest();
		String chapterId = request2.getParameter("chapter1");
		String source = request2.getParameter("source");
		String itemType = request2.getParameter("itemType");
		String item1 = new String(request2.getParameter("item1")
			.getBytes("gbk"), "utf-8");
		String a = new String(request2.getParameter("a")
			.getBytes("gbk"), "utf-8");
		String b = new String(request2.getParameter("b")
			.getBytes("gbk"), "utf-8");
		String c = new String(request2.getParameter("c")
			.getBytes("gbk"), "utf-8");
		String d = new String(request2.getParameter("d")
			.getBytes("gbk"), "utf-8");
		String question = new String(request2.getParameter("question")
			.getBytes("gbk"), "utf-8");
		String answer = new String(request2.getParameter("answer")
			.getBytes("gbk"), "utf-8");
		String[] choieces = request2.getParameterValues("choieces");
		String analysization = new String(request2.getParameter(
			"analysization").getBytes("gbk"), "utf-8");
		boolean notNull = true;
		if (chapterId != null && !"".equals(chapterId)
			&& source != null && !"".equals(source)) {
		    if (request2.getParameter("questionfile") == null) {
			if (itemType.equals("1")) {
			    if (item1 == null || "".equals(item1) || a == null
				    || "".equals(a) || b == null
				    || "".equals(b) || c == null
				    || "".equals(c) || d == null
				    || "".equals(d) || choieces.length < 1) {
				notNull = false;
			    }
			} else {
			    if (question == null || "".equals(question)) {
				notNull = false;
			    }
			}
		    }
		    if (request2.getParameter("answerfile") == null) {
			if (itemType.equals("1")) {
			    if (choieces == null) {
				notNull = false;
			    }
			} else {
			    if (answer == null || "".equals(answer)) {
				notNull = false;
			    }
			}
		    }
		} else {
		    notNull = false;
		}
		if (notNull) {
		    Files files = su.getFiles();
		    String queImage = null;
		    String ansImage = null;
		    String anaImage = null;
		    for (int i = 0; i < files.getCount(); i++) {
			File file = files.getFile(i);
			if (!file.isMissing()) {
			    pathString = new StringBuffer("/image/examination/");
			    int pos = file.getFileName().lastIndexOf(".");
			    pathString.append(Utilities.makeImageName())
				    .append(file.getFileName().substring(pos));

			    java.io.File imgFile = new java.io.File(request
				    .getSession().getServletContext()
				    .getRealPath(pathString.toString()));
			    while (imgFile.exists()) {
				pathString = new StringBuffer(
					"/image/examination/");
				pathString.append(Utilities.makeImageName())
					.append(file.getFileName().substring(
						pos));
				imgFile = new java.io.File(request.getSession()
					.getServletContext()
					.getRealPath(pathString.toString()));
			    }

			    try {
				file.saveAs(pathString.toString(),
					SmartUpload.SAVE_VIRTUAL);
			    } catch (SmartUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			    }
			    if (file.getFieldName().equals("questionfile")) {
				queImage = pathString.toString();
			    } else if (file.getFieldName().equals("anserfile")) {
				ansImage = pathString.toString();
			    } else if (file.getFieldName().equals(
				    "analysizefile")) {
				anaImage = pathString.toString();
			    }
			}
		    }
		    Examination examination = new Examination();
		    String courseidString = ((Course) request.getSession()
			    .getAttribute("course")).getCourseid();
		    examination.setCourseid(courseidString);
		    examination.setChapterid(chapterId);
		    examination.setKnowledgeid(Integer.parseInt(source));
		    int type = Integer.parseInt(itemType);
		    examination.setType(type);
		    if (type == 1) {
			if (queImage == null) {
			    StringBuffer buffer = new StringBuffer();
			    buffer.append(item1.trim()).append("@@@");
			    buffer.append(a.trim()).append("##").append(b.trim())
				    .append("##").append(c.trim()).append("##")
				    .append(d.trim());
			    examination.setQuestion(buffer.toString());
			} else {
			    examination.setQuestionpath(queImage);
			    examination.setQuestion("img");
			}
			if (choieces.length == 1) {
			    examination.setAnswer(choieces[0]);
			} else {
			    StringBuffer buffer = new StringBuffer();
			    for (int j = 0; j < choieces.length; j++) {
				buffer.append(choieces.clone()[j]);
				if (j < choieces.length) {
				    buffer.append(",");
				}
			    }
			    buffer.replace(buffer.length()-1, buffer.length(), "");
			    examination.setAnswer(buffer.toString());
			}
		    } else {
			if (queImage == null){
			    examination.setQuestion(question.trim());
			}else{
			    examination.setQuestion("img");
			    examination.setQuestionpath(queImage);
			}
			if(ansImage == null){
			    examination.setAnswer(answer.trim());
			}else{
			    examination.setAnswer("img");
			    examination.setAnswerpath(ansImage);
			}
		    }
		    if(anaImage == null){
			examination.setAnalysis(analysization.trim());
		    }else{
			examination.setAnalysispath(anaImage);
		    }
		    Examinationbean examinationbean = new Examinationbean();
		    if (examinationbean.addExamination(examination)) {
			request.setAttribute("success", "true");
		    } else {
			request.setAttribute("success", "false");
		    }
		    request.getRequestDispatcher(
			    "../teacher/inputItem.jsp").forward(
			    request, response);
		} else {
		    request.setAttribute("error", "1");
		    request.getRequestDispatcher("../teacher/inputItem.jsp").forward(request, response);
		}
	    }
	}
    }
}
